<?php

namespace app\admin\behavior;

use think\Log;
use think\Request;
use think\Exception;
use think\exception\HttpException;
use app\common\exception\RedirectException;
use think\facade\Session;
use think\Db;

/**
 *  run 方法在没有制定特别的标签名称 作为默认的执行方法体
 *  如果定义了制定标签的方法体 那么会执行同名的方法体
 */
class AuthFilter
{
    private $ignorePath = ['captcha', 'admin/account/login', 'admin/account/register', 'admin/account/forget'];

    public function run(Request $request,$params)
    {
        if (!in_array($request->path(), $this->ignorePath)) {
            $user = json_decode(base64_decode(decrypt(cookie('zbc'))));
            if (empty($user)) {
                // //抛出没有登陆异常
                throw new RedirectException();
            }
            $request->user = $user;
            $result = Db::query('select DISTINCT p.`key`,p.url from zbc_manager_user_role as ur join zbc_manager_role as r on ur.roleId = r.id join zbc_manager_role_permission as rp on r.id = rp.roleId join zbc_manager_permission as p on rp.permissionId = p.id where ur.userId = ?', [$user->id]);
            $permissions = [];
            $urls = [];
            foreach($result as $val){
                array_push($permissions,$val['key']);
                array_push($urls,$val['url']);
            }
            Session::set('permissions', $permissions);
            Session::set('urls', $urls);
        }
    }
}
